﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Utilities.Reflection
{
    public class LinkedProperty
    {
        public object SrcObject { get; set; }
        public PropertyInfo SrcProperty { get; set; }
        public object DstObject { get; set; }
        public PropertyInfo DstProperty { get; set; }
    }

    public static class GlobalWatcher
    {
        private static List<LinkedProperty> linkedProperties = new List<LinkedProperty>();

        public static LinkedProperty LinkProperties(object srcObject, string srcPropertyName, object dstObject, string dstPropertyName)
        {
            PropertyInfo srcProperty = srcObject.GetType().GetProperty(srcPropertyName);
            PropertyInfo dstProperty = dstObject.GetType().GetProperty(dstPropertyName);

            LinkedProperty linkedProperty = new LinkedProperty
            {
                SrcObject = srcObject,
                SrcProperty = srcProperty,
                DstObject = dstObject,
                DstProperty = dstProperty
            };
            linkedProperties.Add(linkedProperty);

            return linkedProperty;
        }

        public static void Update()
        {
            foreach (LinkedProperty linkedProperty in linkedProperties)
                Update(linkedProperty);
        }
        public static void Update(LinkedProperty linkedProperty)
        {
            object value = linkedProperty.SrcProperty.GetGetMethod().Invoke(linkedProperty.SrcObject, null);
            linkedProperty.DstProperty.GetSetMethod().Invoke(linkedProperty.DstObject, new object[] { value });
        }
    }
}
